// SimulationController.ts
import { eventQueue } from '../core/EventQueue'
import { setCurrentTime } from '../core/SimulationClock'
import { delay } from '../utils/Delay'
import SimulationSpeed from '../core/SimulationSpeed'
import { modeling } from './ModelBuilder'
import { dispatcher } from '../core/Dispatcher'
import { clearReadyProducts } from '../core/ReadyProducts'
import { messageTransfer } from '../messaging/MessageTransfer'

type SimStatus = 'idle' | 'running' | 'paused' | 'stopped'

class SimulationController {
  private status: SimStatus = 'idle'
  private pausedResolver: (() => void) | null = null
  private shouldStop: boolean = false

  public setStatus(status: 'running' | 'paused' | 'stopped' | 'resume'): void {
    if (status === 'running') {
      this.start()
    } else if (status === 'paused') {
      this.pause()
    } else if (status === 'stopped') {
      this.stop()
    } else if (status === 'resume') {
      this.resume()
    }
  }
  public changeSpeed(speed: number): void {
    SimulationSpeed.setSpeed = Number(speed)
  }

  getStatus(): SimStatus {
    return this.status
  }

  async start(): Promise<void> {
    //清空一下数据
    this.clearAll()
    if (this.status !== 'idle' && this.status !== 'stopped') return

    console.log('[Sim] ✅ 开始仿真')
    this.status = 'running'
    this.shouldStop = false
    let lastEventTime = 0
    modeling() // 初始化模型（只运行一次）
    while (!eventQueue.isEmpty()) {
      if (this.shouldStop) break
      if (this.status === ('paused' as SimStatus)) {
        await this.waitUntilResume()
      }

      const event = eventQueue.dequeue()
      if (event) {
        const simDelay = event.time - lastEventTime
        lastEventTime = event.time
        const waitMs = (simDelay * 1000) / SimulationSpeed.getSpeed
        await delay(waitMs)
        //发送仿真时间
        messageTransfer('simTime', null, event.time)
        setCurrentTime(event.time)
        event.action()
      }
    }

    if (this.status !== ('paused' as SimStatus)) {
      this.status = 'stopped'
      console.log('[Sim] 🛑 仿真完成或已停止')
    }
  }

  pause(): void {
    if (this.status === 'running') {
      this.status = 'paused'
      console.log('[Sim] ⏸️ 暂停')
    }
  }

  resume(): void {
    if (this.status === 'paused') {
      this.status = 'running'
      console.log('[Sim] ▶️ 重启')
      this.pausedResolver?.()
      this.pausedResolver = null
    }
  }

  stop(): void {
    this.shouldStop = true
    this.status = 'stopped'
    this.clearAll()
    console.log('[Sim] ❌ 仿真停止')
  }

  private waitUntilResume(): Promise<void> {
    return new Promise((resolve) => {
      this.pausedResolver = resolve
    })
  }

  private clearAll(): void {
    //清空队列
    eventQueue.clear()
    //重置时间
    setCurrentTime(0)
    //重置速度
    SimulationSpeed.setSpeed = 1
    //重置模型状态
    dispatcher.clear()
    //清空就绪产品队列
    clearReadyProducts()
  }
}

export const simController = new SimulationController()
